import {create} from "zustand";
import {persist} from "zustand/middleware";
import {LoginModel, Response} from "@/api/interface/auth.ts";
import {API} from "@/api";
import {Consumer, Function, Producer} from "@/interfaces";
import {STORAGE} from "@/const";

interface User {
    name: string;
    age: number;
}

export interface AuthStoreState {
    token: string;
    user: User,
    setToken: (token: string) => void,
    setUser: Consumer<User>,
    login: Function<LoginModel, Promise<void>>,
    auth: Producer<Promise<void>>,
    logout: () => Promise<void>,
}

const useAuthStore = create(
    persist<AuthStoreState>(
        (set, get) => ({
            token: "",
            user: {
                name: "",
                age: 0
            },
            setToken: (token: string) => {
                set({token});
            },
            setUser(user: User) {
                set({user})
            },
            async login(user: LoginModel) {
                const {setToken} = get()
                return API.login(user).then((res: Response<string>) => {
                    setToken(res.data)
                })
            },
            async auth() {
                const {setUser} = get()
                return API.auth().then(({data}: Response<User>) => {
                    setUser(data)
                })
            },
            async logout() {
                const {setToken, setUser} = get()
                return API.logout().then(() => {
                }).finally(() => {
                    setToken('');
                    setUser({name: '', age: -1})
                })
            }
        }),
        {
            name: STORAGE.AUTH_KEY
        }
    )
)
export default useAuthStore